package com.example.shirospringboottest.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.example.shirospringboottest.shiro.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;

@Configuration
public class ShiroConfigure {
    /**
     * 注册凭证匹配器
     * 配置加密算法和迭代加盐次数
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher createHashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        hashedCredentialsMatcher.setHashAlgorithmName("md5");

        hashedCredentialsMatcher.setHashIterations(2);

        return hashedCredentialsMatcher;
    }

    @Bean
    public AuthorizingRealm getMyRealm(HashedCredentialsMatcher hashedCredentialsMatcher) {
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return myRealm;
    }

    @Bean
    public SecurityManager getDefaultWebSecurityManager(AuthorizingRealm authorizingRealm, SessionManager sessionManager) {

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(authorizingRealm);

        /**
         * 注入SessionManager
         */
        defaultWebSecurityManager.setSessionManager(sessionManager);

        return defaultWebSecurityManager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        /**
         * 用户认证失败后跳转的页面
         * 登陆页面会自动放行，无需添加
         */
        shiroFilterFactoryBean.setLoginUrl("/loginPage");

        shiroFilterFactoryBean.setSuccessUrl("/index-x");

        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorizedPage");

        HashMap<String, Filter> filterMap = new HashMap<>();

        filterMap.put("myLogoutFilter", getLogoutFilter());

        //filterMap.put("myFormAuthenticationFilter",getFormAuthenticationFilter());
        /**
         * 不知道默认的过滤器还能不能继续使用
         */
        shiroFilterFactoryBean.setFilters(filterMap);

        /**
         * Shiro内置过滤器，可以实现权限相关的拦截器
         * 常用的过滤器：
         * 1.anno:无需认证（登陆）即可访问
         * 2.authc:必须认证才可以访问
         * 3.user:如果使用了RememberME的功能，可以直接跳转
         * 4.perms:该资源必须资源权限才可以访问
         * 5.role:该资源必须得到角色权限才可以访问
         * 6.
         * 7.
         *
         * 千万要注意map中的顺序
         * 错误：HashMap<String, String> filterChainDefinitionMap = new HashMap<>();
         * 为了保证顺序，应该使用LinkedHashMap
         * 放行login.html
         */
        HashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        /**
         * 放行到控制器的登陆请求
         */
        filterChainDefinitionMap.put("/loginController", "anon");
        //filterChainDefinitionMap.put("/loginController", "myFormAuthenticationFilter");

        /**
         * 这样是无法放行静态资源的 filterChainDefinitionMap.put("*.js", "anon");
         * 要这样才能放行静态资源
         */
        filterChainDefinitionMap.put("/**/*.js", "anon");
        filterChainDefinitionMap.put("/**/*.css", "anon");
        //放行图片
        filterChainDefinitionMap.put("/**/*.gif", "anon");
        filterChainDefinitionMap.put("/**/*.png", "anon");
        filterChainDefinitionMap.put("/**/*.jpg", "anon");

        filterChainDefinitionMap.put("/**/*.ico", "perms[refuse]"); //直接拦截，省的天天favicon.ico异常

        /**
         * 因为授权不足而被拦截的请求会跳转到之前的
         * shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorizedPage"); 页面
         */
        filterChainDefinitionMap.put("/task/AddTask", "perms[admin]");
        filterChainDefinitionMap.put("/logout", "myLogoutFilter");

        /**
         * 配置记住我的过滤器，当浏览器记住我了以后，不会走原来的/userLogin
         *                     而是走/userLogin完成之后的/findMoreMenus
         *                     此时就要跳转user过滤器，执行记住我的相关操作
         *                     这个user过滤器帮我们判断用户有没有登陆
         */

        filterChainDefinitionMap.put("/index", "user");

        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);


        return shiroFilterFactoryBean;
    }

    // 加入注解的使用，不加入这个注解不生效
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    //@Bean()
    public LogoutFilter getLogoutFilter() {
        LogoutFilter logoutFilter = new LogoutFilter();

        logoutFilter.setRedirectUrl("/loginPage");

        return logoutFilter;
    }

    /**
     * 自动验证用户名密码的过滤器，好像没什么用
     *
     * @return
     */
    @Bean(name = "authc")
    public FormAuthenticationFilter getFormAuthenticationFilter() {
        FormAuthenticationFilter formAuthenticationFilter = new FormAuthenticationFilter();

        formAuthenticationFilter.setUsernameParam("userName");

        return formAuthenticationFilter;
    }

    @Bean
    public SessionManager getSessionManager(SimpleCookie simpleCookie) {
        DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();

        defaultWebSessionManager.setDeleteInvalidSessions(true);

        defaultWebSessionManager.setGlobalSessionTimeout(1000 * 60 * 60 * 24 * 7);
        /**
         * 记得注入
         * org.apache.shiro.crypto.CryptoException 异常
         */
        //defaultWebSessionManager.setSessionIdCookie(simpleCookie);

        return defaultWebSessionManager;
    }

    @Bean
    public SimpleCookie getSimpleCookie() {
        SimpleCookie simpleCookie = new SimpleCookie();

        simpleCookie.setName("rememberMe");

        simpleCookie.setMaxAge(60 * 60 * 24 * 7);

        return simpleCookie;
    }

    @Bean
    public CookieRememberMeManager getCookieRememberMeManager(SimpleCookie simpleCookie) {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();

        cookieRememberMeManager.setCookie(simpleCookie);

        return cookieRememberMeManager;
    }

    /**
     * 创建ShiroDialect对象，用于thymeleaf和shiro标签的结合使用
     * 之后在thymeleaf中就可以使用<div shiro:hasPermission="userAdd"></div> 来控制div是否显示
     * @return
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
